package com.lvmama.pangolin.kafka;


import com.lvmama.pangolin.common.Constant;
import com.lvmama.pangolin.common.DateUtil;
import com.lvmama.pangolin.common.StringTools;
import com.lvmama.pangolin.entity.ConvertTask;
import com.lvmama.pangolin.entity.LogVO;
import com.lvmama.pangolin.entity.hotel.HotelCdetail;
import com.lvmama.pangolin.entity.hotel.HotelPdetail;
import com.lvmama.pangolin.entity.spider.TicketCommodity;
import com.lvmama.pangolin.entity.spider.TicketProduct;
import com.lvmama.pangolin.hotel.service.HotelCdetailService;
import com.lvmama.pangolin.hotel.service.HotelPdetailService;
import com.lvmama.pangolin.mt.service.TicketCdetailMtService;
import com.lvmama.pangolin.mt.service.TicketPdetailMtService;
import com.lvmama.pangolin.qnr.service.QNRTicketCommodityDetailService;
import com.lvmama.pangolin.qnr.service.QNRTicketCommodityService;
import com.lvmama.pangolin.service.ConvertTaskService;
import com.lvmama.pangolin.service.OperLogService;
import com.lvmama.pangolin.tc.service.TCTicketCommodityDetailService;
import com.lvmama.pangolin.tc.service.TCTicketCommodityService;
import com.lvmama.pangolin.tn.service.TNTicketCommodityDetailService;
import com.lvmama.pangolin.tn.service.TNTicketCommodityService;
import com.lvmama.pangolin.xc.service.XCTicketCommodityDetailService;
import com.lvmama.pangolin.xc.service.XCTicketCommodityService;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;

import java.net.URLDecoder;
import java.sql.Timestamp;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;


public class SpiderProductProcesser extends FlumeToKafkaConsumer<String> {

    private final Logger logger = Logger.getLogger(this.getClass());

    @Autowired
    private TCTicketCommodityService tcTicketCommodityService;
    
    @Autowired
    private TCTicketCommodityDetailService tcTicketCommodityDetailService;
    
    @Autowired
    private XCTicketCommodityService xcTicketCommodityService;
    
    @Autowired
    private XCTicketCommodityDetailService xcTicketCommodityDetailService;
    
    @Autowired
    private TNTicketCommodityService tnTicketCommodityService;
    
    @Autowired
    private TNTicketCommodityDetailService tnTicketCommodityDetailService;
    
    @Autowired
    private QNRTicketCommodityService qnrTicketCommodityService;
    
    @Autowired
    private QNRTicketCommodityDetailService qnrTicketCommodityDetailService;
   
    @Autowired
    private ConvertTaskService convertTaskService;
    
    @Autowired
    private OperLogService operLogService;
    
    @Autowired
    private HotelCdetailService hotelCdetailService;
    
    @Autowired
    private HotelPdetailService hotelPdetailService;
	@Autowired
	private TicketCdetailMtService cdetailMtService;
	@Autowired
	private TicketPdetailMtService pdetailMtService;

    @Override
    public void process(String message)
    {
        //logger.info(" process message : " + message);
        Pattern pattern = Pattern.compile("\\?(.*?)\\ ");
        Matcher matcher = pattern.matcher(message);
        while(matcher.find())
        {
        	message = matcher.group(1);
        }
        Map<String,List<String>> msgMap = parseMsgData(message);
        String type = getString(msgMap,"type",0); 
        //任务完成信息
        if("TASK".equalsIgnoreCase(type))
        {
//        	ConvertTask convertTask = new ConvertTask();
//        	convertTask.setBusinessType(getString(msgMap,"business_type",0));
//        	convertTask.setTaskId(getString(msgMap,"task_id",0));
//        	convertTask.setParamCode(getString(msgMap,"timer_param",0));
//        	convertTask.setCompanyCode(getString(msgMap,"company_code",0));
//        	convertTask.setGranularity(getString(msgMap,"timer_granularity",0));
//        	convertTask.setGranularityValue(getString(msgMap,"city_code",0));
//        	convertTask.setStatus("0");
//        	convertTask.setRunNum(0);
//        	convertTask.setRetryNum(3);;
//        			
//        	convertTaskService.insert(convertTask);
        }
        //门票数据信息
        else if ("TICKET".equalsIgnoreCase(type))
        {
        	TicketProduct product = parseTicketProduct(msgMap);
        	List<TicketCommodity> commodityList = parseTicketCommodify(msgMap);
        	String companyCode = product.getCompany_code();
        	String timer_param = "";
        	if(Constant.TN_C_CODE.equalsIgnoreCase(companyCode))
        	{
        		timer_param = "TN_Ticket_Grab";
        		saveTN(product,commodityList);
        		
        	}else if(Constant.XC_C_CODE.equalsIgnoreCase(companyCode))
        	{
        		timer_param = "XC_Ticket_Grab";
        		saveXC(product,commodityList);
        		
        	}else if(Constant.QNR_C_CODE .equalsIgnoreCase(companyCode))
        	{
        		timer_param = "QNR_Ticket_Grab";
        		saveQNR(product,commodityList);
        		
        	}else if(Constant.TC_C_CODE.equalsIgnoreCase(companyCode))
        	{
        		timer_param = "TC_Ticket_Grab";
        		saveTC(product,commodityList);
        	}else if(Constant.MT_C_CODE.equalsIgnoreCase(companyCode))
        	{
        		timer_param = "MT_Ticket_Grab";
        		saveMT(product,commodityList);
        	}
        	ConvertTask convertTask = new ConvertTask();
        	convertTask.setBusinessType("TICKET");
        	convertTask.setTaskId(product.getTask_id());
        	convertTask.setParamCode(timer_param);
        	convertTask.setCompanyCode(product.getCompany_code());
        	convertTask.setGranularity("1");
        	convertTask.setGranularityValue(product.getCity_code());
        	convertTask.setStatus("0");
        	convertTask.setRunNum(0);
        	convertTask.setRetryNum(3);
        	convertTask.setProductId(product.getProduct_id());
        	convertTask.setInsertTime(new Date());
        			
        	convertTaskService.insert(convertTask);
        	
        }
        else if ("HOTEL".equalsIgnoreCase(type))
        {
        	
        	try
        	{
        		HotelPdetail product = parseHotelProduct(msgMap);
            	List<HotelCdetail> commodityList = parseHotelCommodify(msgMap);
            	
            	hotelPdetailService.deleteBytaskAndProd(product);
            	hotelPdetailService.save(product);
            	if(commodityList != null && !commodityList.isEmpty())
            	{
            		hotelCdetailService.deleteBytaskAndProd(commodityList.get(0));
            		hotelCdetailService.saveList(commodityList);
            	}
            	
            	
            	ConvertTask convertTask = new ConvertTask();
            	convertTask.setBusinessType("HOTEL");
            	convertTask.setTaskId(product.getTaskId());
            	convertTask.setParamCode("");
            	convertTask.setCompanyCode(product.getCompanyCode());
            	convertTask.setGranularity("1");
            	convertTask.setGranularityValue(product.getCityCode());
            	convertTask.setStatus("0");
            	convertTask.setRunNum(0);
            	convertTask.setRetryNum(3);
            	convertTask.setProductId(product.getProductId());
            	convertTask.setInsertTime(new Date());
            	convertTaskService.insert(convertTask);
        	}catch (Exception e)
        	{
        		logger.error("数据入库失败!", e);
        	}
        	
        }
        else if("LOG".equalsIgnoreCase(type))
        {
        	try
        	{
        		LogVO log = parseOperLog(msgMap);
        		operLogService.insertOperLog(log);
        	}catch(Exception e)
        	{
        		logger.error("操作日志入表失败！", e);
        	}
        	
        }
        
       
    }
    
    public void saveMT(TicketProduct product, List<TicketCommodity> commodityList) {
    	try {
    		pdetailMtService.deleteBytaskAndProd(product);
        	pdetailMtService.insertSelective(product);
        	if(commodityList!=null && !commodityList.isEmpty()){
        		cdetailMtService.deleteByTaskAndProd(commodityList.get(0));
        		for(TicketCommodity item:commodityList){
            		cdetailMtService.insertSelective(item);
            	}
        	}
		} catch (Exception e) {
			String message = "商品数据入表失败！product_id : "+product.getProduct_id(); 
			logger.error(message, e);
		}
    	
	}

	private void saveTN(TicketProduct product,List<TicketCommodity> commodityList)
    {
    	tnTicketCommodityService.deleteBytaskAndProd(product);
    	tnTicketCommodityService.insertSelective(product);
    	if(commodityList != null && !commodityList.isEmpty())
    	{
    		tnTicketCommodityDetailService.deleteByTaskAndProd(commodityList.get(0));
    		for (TicketCommodity ticketCommodity : commodityList)
			{
    			try
    			{
    				tnTicketCommodityDetailService.insertSelective(ticketCommodity);
    			}catch(Exception e)
    			{
    				String message = "商品数据入表失败！product_id : "+ticketCommodity.getProduct_id()+" commodify_id : " + ticketCommodity.getCommodity_id(); 
    				logger.error(message, e);
    			}
    			
			}
    	}
    }
    
    private void saveXC(TicketProduct product,List<TicketCommodity> commodityList)
    {
    	xcTicketCommodityService.deleteBytaskAndProd(product);
    	xcTicketCommodityService.insertSelective(product);
    	if(commodityList != null && !commodityList.isEmpty())
    	{
    		xcTicketCommodityDetailService.deleteByTaskAndProd(commodityList.get(0));
    		for (TicketCommodity ticketCommodity : commodityList)
			{
    			try
    			{
    				xcTicketCommodityDetailService.insertSelective(ticketCommodity);
    			}catch(Exception e)
    			{
    				String message = "商品数据入表失败！product_id : "+ticketCommodity.getProduct_id()+" commodify_id : " + ticketCommodity.getCommodity_id(); 
    				logger.error(message, e);
    			}
    			
			}
    	}
    }
    
    private void saveQNR(TicketProduct product,List<TicketCommodity> commodityList)
    {
    	qnrTicketCommodityService.deleteBytaskAndProd(product);
    	qnrTicketCommodityService.insertSelective(product);
    	if(commodityList != null && !commodityList.isEmpty())
    	{
    		qnrTicketCommodityDetailService.deleteByTaskAndProd(commodityList.get(0));
    		for (TicketCommodity ticketCommodity : commodityList)
			{
    			try
    			{
    				qnrTicketCommodityDetailService.insertSelective(ticketCommodity);
    			}catch(Exception e)
    			{
    				String message = "商品数据入表失败！product_id : "+ticketCommodity.getProduct_id()+" commodify_id : " + ticketCommodity.getCommodity_id(); 
    				logger.error(message, e);
    			}
    			
			}
    	}
    }
    
    private void saveTC(TicketProduct product,List<TicketCommodity> commodityList)
    {
    	tcTicketCommodityService.deleteBytaskAndProd(product);
    	tcTicketCommodityService.insertSelective(product);
    	if(commodityList != null && !commodityList.isEmpty())
    	{
    		tcTicketCommodityDetailService.deleteByTaskAndProd(commodityList.get(0));
    		for (TicketCommodity ticketCommodity : commodityList)
			{
    			try
    			{
    				tcTicketCommodityDetailService.insertSelective(ticketCommodity);
    			}catch(Exception e)
    			{
    				String message = "商品数据入表失败！product_id : "+ticketCommodity.getProduct_id()+" commodify_id : " + ticketCommodity.getCommodity_id(); 
    				logger.error(message, e);
    			}
    			
			}
    	}
    }
    
    private List<TicketCommodity> parseTicketCommodify(Map<String,List<String>> msgMap)
    {
    	List<TicketCommodity> commodityList = null;
    	if(msgMap != null && !msgMap.isEmpty())
    	{
    		commodityList = new ArrayList<TicketCommodity>();
        	List<String> idList = msgMap.get("commodity_id");
        	
        	if(idList != null && !idList.isEmpty())
        	{
        		TicketCommodity commodify = null;
        		for(int i = 0;i < idList.size();i++)
        		{
        			commodify = new TicketCommodity();
        			commodify.setCommodity_id(getString(msgMap,"commodity_id",i));
        			commodify.setCommodity_type(getString(msgMap,"commodity_type",i));
        			commodify.setCommodity_name(getString(msgMap,"commodity_name",i));
        			commodify.setCommodity_url(getString(msgMap,"commodity_url",i));
        			commodify.setSale_cond(getString(msgMap,"sale_cond",i));
        			commodify.setRefund_cond(getString(msgMap,"refund_cond",i));
        			commodify.setRack_rate(getString(msgMap,"rack_rate",i));
        			commodify.setSale_price(getString(msgMap,"sale_price",i));
        			commodify.setPreferential(getString(msgMap,"preferential",i));
        			commodify.setPrice_list_id(getString(msgMap,"price_list_id",i));
        			commodify.setDetail_id(getString(msgMap,"detail_id",0));
        			commodify.setProduct_id(getString(msgMap,"product_id",0));
        			commodify.setTask_id(getString(msgMap,"task_id",0));
        			commodify.setCity_code(getString(msgMap,"city_code",0));
					commodify.setEfficient_time(getString(msgMap, "booking_effective_time", 0));
					Date date = new Date();
        			try
        			{
        				commodify.setTask_date(DateUtil.formatString(getString(msgMap,"task_date",0), "yyyy-MM-dd"));
        			}
        			catch (Exception e)
        			{
        				commodify.setTask_date(date);
        			}
        			commodify.setCreate_time(new Timestamp(date.getTime()));
        			commodify.setUpdate_time(date);
        			
        			commodityList.add(commodify);
        		}
        		
        		
        	}
    	}
    	return commodityList;
    	
    }
    private TicketProduct parseTicketProduct(Map<String,List<String>> msgMap)
    {
    	Date date = new Date();
    	TicketProduct product = new TicketProduct();
    	product.setDetail_id(getString(msgMap,"detail_id",0));
    	product.setCity_code(getString(msgMap,"city_code",0));
    	product.setCompany_code(getString(msgMap,"company_code",0));
    	product.setCreate_time(new Timestamp(date.getTime()));
    	product.setDetail_url(getString(msgMap,"detail_url",0));
    	product.setImage_num(getString(msgMap,"image_num",0));
    	product.setIntroduction(getString(msgMap,"introduction",0));
    	product.setLowest_price(getString(msgMap,"lowest_price",0));
    	product.setPlatform_code(getString(msgMap,"platform_code",0));
    	product.setProduct_id(getString(msgMap,"product_id",0));
    	product.setRsrv_str1(getString(msgMap,"rsrv_str1",0));
    	product.setRsrv_str2(getString(msgMap,"rsrv_str2",0));
    	product.setRsrv_str3(getString(msgMap,"rsrv_str3",0));
    	product.setSale_count(getString(msgMap,"sale_count",0));
    	product.setScenery_addr(getString(msgMap,"scenery_addr",0));
    	product.setScenery_name(getString(msgMap,"scenery_name",0));
    	product.setScore(getString(msgMap,"score",0));
    	product.setScore_tag(getString(msgMap,"score_tag",0));
    	product.setSnapshot_addr(getString(msgMap,"snapshot_addr",0));
    	product.setStar_level(getString(msgMap,"star_level",0));
    	product.setLv_product_id(getString(msgMap,"lv_product_id",0));
    	try
		{
			product.setTask_date(DateUtil.formatString(getString(msgMap,"task_date",0), "yyyy-MM-dd"));
		}
		catch (Exception e)
		{
			product.setTask_date(date);
		}
    	product.setTask_id(getString(msgMap,"task_id",0));
    	product.setUpdate_time(new Timestamp(date.getTime()));
    	
    	return product;
    }
    
    private HotelPdetail parseHotelProduct(Map<String,List<String>> msgMap)
    {
    	Date date = new Date();
    	HotelPdetail product = new HotelPdetail();
    	product.setDetailId(getString(msgMap,"detail_id",0));
    	product.setCityCode(getString(msgMap,"city_code",0));
    	product.setCompanyCode(getString(msgMap,"company_code",0));
    	product.setCreateTime(new Timestamp(date.getTime()));
    	product.setDetailUrl(getString(msgMap,"detail_url",0));
    	product.setImageNum(getString(msgMap,"image_num",0));
    	product.setIntroduction(getString(msgMap,"introduction",0));
    	product.setLowestPrice(getString(msgMap,"lowest_price",0));
    	product.setPlatformCode(getString(msgMap,"platform_code",0));
    	product.setProductId(getString(msgMap,"product_id",0));
    	product.setRsrvStr1(getString(msgMap,"rsrv_str1",0));
    	product.setRsrvStr2(getString(msgMap,"rsrv_str2",0));
    	product.setRsrvStr3(getString(msgMap,"rsrv_str3",0));
    	product.setSaleCount(getString(msgMap,"sale_count",0));
    	product.setHotelAddr(getString(msgMap,"hotel_addr",0));
    	product.setHotelName(getString(msgMap,"hotel_name",0));
    	product.setScore(getString(msgMap,"score",0));
    	product.setScoreTag(getString(msgMap,"score_tag",0));
    	product.setSnapshotAddr(getString(msgMap,"snapshot_addr",0));
    	product.setStarLevel(getString(msgMap,"star_level",0));
    	product.setLvProductId(getString(msgMap,"lv_product_id",0));
    	
    	
    	try
		{
    		product.setComeDate(DateUtil.formatString(getString(msgMap,"come_date",0), "yyyy-MM-dd"));
        	product.setLeaveDate(DateUtil.formatString(getString(msgMap,"leave_date",0), "yyyy-MM-dd"));
			product.setTaskDate(DateUtil.formatString(getString(msgMap,"task_date",0), "yyyy-MM-dd"));
		}
		catch (Exception e)
		{
			product.setTaskDate(date);
			product.setComeDate(date);
			product.setLeaveDate(date);
		}
    	product.setTaskId(getString(msgMap,"task_id",0));
    	product.setUpdateTime(new Timestamp(date.getTime()));
    	
    	return product;
    }
    
    private List<HotelCdetail> parseHotelCommodify(Map<String,List<String>> msgMap)
    {
    	List<HotelCdetail> commodityList = null;
    	if(msgMap != null && !msgMap.isEmpty())
    	{
    		commodityList = new ArrayList<HotelCdetail>();
        	List<String> idList = msgMap.get("commodity_id");
        	
        	if(idList != null && !idList.isEmpty())
        	{
        		HotelCdetail commodify = null;
        		for(int i = 0;i < idList.size();i++)
        		{
        			commodify = new HotelCdetail();
        			commodify.setCommodityId(getString(msgMap,"commodity_id",i));
        			commodify.setRoomType(getString(msgMap,"room_type",i));
        			commodify.setCommodityName(getString(msgMap,"commodity_name",i));
        			commodify.setCommodityUrl(getString(msgMap,"commodity_url",i));
        			commodify.setArea(getString(msgMap,"area",i));
        			commodify.setFloor(getString(msgMap,"floor",i));
        			commodify.setBedType(getString(msgMap,"bed_type",i));
        			commodify.setBreakfast(getString(msgMap,"breakfast",i));
        			commodify.setBroadband(getString(msgMap,"broadband",i));
        			
        			commodify.setWindow(getString(msgMap,"window",i));
        			commodify.setIncreaseBed(getString(msgMap,"increase_bed",i));
        			commodify.setPeopleNum(getString(msgMap,"people_num",i));
        			commodify.setCancelRule(getString(msgMap,"cancel_rule",i));
        			
        			commodify.setSalePrice(getString(msgMap,"sale_price",i));
        			commodify.setPreferential(getString(msgMap,"preferential",i));
        			commodify.setPriceListId(getString(msgMap,"price_list_id",i));
        			commodify.setDetailId(getString(msgMap,"detail_id",0));
        			commodify.setProductId(getString(msgMap,"product_id",0));
        			commodify.setTaskId(getString(msgMap,"task_id",0));
        			commodify.setCityCode(getString(msgMap,"city_code",0));
        			commodify.setCompanyCode(getString(msgMap,"company_code",0));
        			Date date = new Date();
        			try
        			{
        				commodify.setTaskDate(DateUtil.formatString(getString(msgMap,"task_date",0), "yyyy-MM-dd"));
        			}
        			catch (Exception e)
        			{
        				commodify.setTaskDate(date);
        			}
        			try
        			{
        				commodify.setUpdateTime(DateUtil.formatString(getString(msgMap,"update_time",0), "yyyy-MM-dd"));
        				commodify.setCreateTime(new Timestamp(DateUtil.formatString(getString(msgMap,"update_time",0), "yyyy-MM-dd HH:mm:ss").getTime()));
        			}
        			catch (Exception e)
        			{
        				commodify.setUpdateTime(date);
        				commodify.setCreateTime(new Timestamp(date.getTime()));
        			}
        			
        			commodityList.add(commodify);
        		}
        		
        		
        	}
    	}
    	return commodityList;
    	
    }
    
    private LogVO parseOperLog(Map<String,List<String>> msgMap)
    {
    	Date date = new Date();
    	LogVO log = new LogVO();
//    	log.setLog_id(Integer.valueOf(getString(msgMap,"log_id",0)));
    	log.setLog_type(getString(msgMap,"log_type",0));
    	log.setCompany_code(getString(msgMap,"company_code",0));
    	log.setBusi_type(getString(msgMap,"busi_type",0));
    	log.setProduct_id(getString(msgMap,"product_id",0));
//    	log.setCommodity_id(getString(msgMap,"commodity_id",0));
    	log.setUrl(getString(msgMap,"url",0));
    	log.setIp(getString(msgMap,"ip",0));
    	log.setBatch_num(getString(msgMap,"batch_num",0));
    	log.setTimer_code(getString(msgMap,"timer_code",0));
    	log.setError_code(getString(msgMap,"error_code",0));
    	log.setError_desc(getString(msgMap,"error_desc",0));
    	log.setRemark(getString(msgMap,"remark",0));
    	log.setTask_id(getString(msgMap,"task_id",0));
    	
    	try
		{
    		log.setTask_date(DateUtil.formatString(getString(msgMap,"task_date",0), "yyyy-MM-dd"));
		}
		catch (Exception e)
		{
			log.setTask_date(date);
		}
    	log.setInsert_time(new Timestamp(date.getTime()));
    	
    	return log;
    }
    
    private String getString(Map<String,List<String>> msgMap, String key,int index)
    {
    	String retStr = "";
    	List<String> strL = msgMap.get(key);
    	if(strL != null && !strL.isEmpty())
    	{
    		if(index >= 0 && index < strL.size())
    		{
    			retStr = strL.get(index);
    		}
    		
    	}
    	return retStr;
    }
    
    private Map<String,List<String>> parseMsgData(String message)
    {
    	Map<String,List<String>> msgMap = new HashMap<String,List<String>>();
    	if(message != null && StringTools.isValid(message))
    	{
    		String[] strArr =  message.split("&");
    		if(strArr != null && strArr.length > 0)
    		{
    			String paramName = null;
    			String paramValue = null;
    			String[] paramArr = null;
    			List<String> list = null;
    			for (String string : strArr)
				{
    				try
    				{
    					paramArr = string.split("=");
    					if(paramArr != null && paramArr.length > 0)
    					{
    						//全部小写
    						paramName = paramArr[0].toLowerCase();
    						if(paramArr.length == 1)
    						{
    							paramValue = "";
    						}
    						else
    						{
    							paramValue = URLDecoder.decode(paramArr[1],"UTF-8");
    						}
            				list = msgMap.get(paramName);
            				if(list == null)
            				{
            					list = new ArrayList<String>();
            					list.add(paramValue);
            					msgMap.put(paramName, list);
            				}
            				else
            				{
            					list.add(paramValue);
            				}
    						
    					}
        				
        				
    				}catch(Exception e)
    				{
    					logger.error("解析转换失败，paramName：" + paramName ,e);
    				}
    				
				}
    		}
    	}
    	return msgMap;
    }
    
    public SpiderProductProcesser(Properties properties, Integer partition,
			List<String> topics)
	{
		super(properties, partition, topics);
	}
    
   
}
